<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="auto">
        <!-- 使用 el-row 和 el-col 实现一行两列布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班次名称" prop="shiftName">
              <el-input style="width: 235px;" v-model="formData.shiftName" placeholder="请输入班次名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班次开始时间" prop="shiftStartTime">
              <el-time-picker  style="width: 235px;" clearable v-model="formData.shiftStartTime" format="HH:mm:ss"
                              value-format="HH:mm:ss"
                              placeholder="选择班次开始时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次结束时间" prop="shiftEndTime">
              <el-time-picker  style="width: 235px;" clearable v-model="formData.shiftEndTime" format="HH:mm:ss"
                              value-format="HH:mm:ss"
                              placeholder="选择班次结束时间"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input style="width: 625px;" v-model="formData.remark" placeholder="请输入备注" type="textarea" rows="3"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 休息时间列表 -->
        <el-form-item label="休息时间列表">
          <div v-for="(item, index) in formData.restTimeList" :key="index" class="rest-time-item">
            <el-row :gutter="5" style="display: flex; align-items: center;justify-content: flex-start">
              <el-input type="hidden" v-model="item.id"/>
              <el-form-item :prop="'restTimeList.' + index + '.id'">
                {{ index + 1 }}.
              </el-form-item>
              <el-form-item :prop="'restTimeList.' + index + '.startTime'" :rules="restTimeRules.startTime">
                <el-time-picker style="width: 150px;margin:0 10px" clearable v-model="item.startTime"
                                format="HH:mm:ss" value-format="HH:mm:ss"
                                placeholder="开始时间" @change="calculateRestTime(index)"/>
              </el-form-item>
              <el-form-item :prop="'restTimeList.' + index + '.endTime'" :rules="restTimeRules.endTime">
                <el-time-picker style="width: 150px;margin-right: 10px" clearable v-model="item.endTime"
                                format="HH:mm:ss" value-format="HH:mm:ss"
                                placeholder="结束时间" @change="calculateRestTime(index)"/>
              </el-form-item>
              <el-form-item :prop="'restTimeList.' + index + '.restTime'" :rules="restTimeRules.restTime">
                <div style="display: flex; align-items: center;width: 120px">
                  <el-input style="width: 70px;" v-model="item.restTime" placeholder="休息时间(分钟)" readonly/>
                  <span style="margin:0 10px">min</span>
                </div>
              </el-form-item>
              <el-form-item :prop="'restTimeList.' + index + '.remark'" :rules="restTimeRules.remark">
                <el-input style="width: 150px" v-model="item.remark" placeholder="备注"/>
              </el-form-item>
              <el-button type="text" size="small" icon="el-icon-delete" @click="removeRestTime(index)"
                         v-if="formData.restTimeList.length > 1" style="margin-left: 10px"></el-button>
            </el-row>
          </div>
          <el-button type="primary" size="small" @click="addRestTime" style="margin-top: 10px;">添加休息时间</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ShiftApi from '@/api/lamp/shift';

export default {
  name: "ShiftForm",
  components: {},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        shiftName: undefined,
        shiftStartTime: undefined,
        shiftEndTime: undefined,
        remark: undefined,
        status: "1", // 默认启用
        restTimeList: [
          {
            startTime: "",
            endTime: "",
            restTime: 0,
            remark: ""
          }
        ]
      },
      // 表单校验
      formRules: {
        shiftName: [{required: true, message: '班次名称不能为空', trigger: 'blur'}],
        shiftStartTime: [{required: true, message: '班次开始时间不能为空', trigger: 'blur'}],
        shiftEndTime: [{required: true, message: '班次结束时间不能为空', trigger: 'blur'}],
        status: [{required: true, message: '状态不能为空', trigger: 'change'}],
      },
      // 休息时间列表的校验规则
      restTimeRules: {
        startTime: [{required: true, message: '开始时间不能为空', trigger: 'blur'}],
        endTime: [{required: true, message: '结束时间不能为空', trigger: 'blur'}],
        restTime: [{required: true, message: '休息时间不能为空', trigger: 'blur'}],
        remark: [{max: 255, message: '备注最多255个字符', trigger: 'blur'}]
      }
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await ShiftApi.getShift(id);
          this.formData = res.data;
          // 如果没有休息时间列表，初始化一个空的
          if (!this.formData.restTimeList || this.formData.restTimeList.length === 0) {
            this.formData.restTimeList = [
              {
                startTime: "",
                endTime: "",
                restTime: 0,
                remark: ""
              }
            ];
          }
          this.dialogTitle = "编辑生产班次";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增生产班次";
      }
    },

    /** 计算休息时间（分钟） */
    calculateRestTime(index) {
      const item = this.formData.restTimeList[index];
      if (item.startTime && item.endTime) {
        // 将时间字符串转换为分钟数进行计算
        const startMinutes = this.timeToMinutes(item.startTime);
        const endMinutes = this.timeToMinutes(item.endTime);

        // 如果结束时间小于开始时间，说明是跨天的情况
        let restMinutes = endMinutes - startMinutes;
        if (restMinutes < 0) {
          restMinutes += 24 * 60; // 加上24小时的分钟数
        }

        item.restTime = restMinutes;
      }
    },

    /** 将时间字符串转换为分钟数 */
    timeToMinutes(timeStr) {
      const [hours, minutes, seconds] = timeStr.split(':').map(Number);
      return hours * 60 + minutes + Math.floor(seconds / 60); // 秒数四舍五入到分钟
    },

    /** 添加休息时间 */
    addRestTime() {
      this.formData.restTimeList.push({
        startTime: "",
        endTime: "",
        restTime: 0,
        remark: ""
      });
    },

    /** 移除休息时间 */
    removeRestTime(index) {
      this.formData.restTimeList.splice(index, 1);
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ShiftApi.updateShift(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await ShiftApi.createShift(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        shiftName: undefined,
        shiftStartTime: undefined,
        shiftEndTime: undefined,
        remark: undefined,
        status: "1", // 默认启用
        restTimeList: [
          {
            startTime: "",
            endTime: "",
            restTime: 0,
            remark: ""
          }
        ]
      };
      this.resetForm("formRef");
    }
  }
};
</script>

<style scoped>
.rest-time-item {
  border: 1px solid #e6e6e6;
  padding: 10px 5px;
  margin-bottom: 10px;
  border-radius: 4px;
}
</style>
